home *** CD-ROM | disk | FTP | other *** search
/ Aminet 48 / Aminet 48 (2002)(GTI - Schatztruhe)[!][Apr 2002].iso / Aminet / docs / mags / AIOV55.lha / AIOIssue55 / examples / 2.6_evenodd_bad.c < prev    next >
Encoding:
C/C++ Source or Header  |  1980-01-01  |  2.2 KB  |  39 lines

  1. /**************************************************/
  2. /* This code will not compile.                    */
  3. /* It assumes even_array is a modifiable pointer. */
  4. /* See if you can guess which line the error will */
  5. /* occur.                                         */
  6. /**************************************************/
  7. #include <stdio.h>
  8.  
  9. int main(void)
  10. {
  11.   int i = 0;
  12.   int even_array[100];    /* create an array with the compiler */
  13.   int * odd_array = NULL; /* int pointer for a "hand-made" array */
  14.   int * odd_array_alias = NULL; /* will be modifying odd_array pointer, but still have to free() the original address. Remember original address with odd_array_alias */
  15.  
  16.   odd_array = (int *) calloc(100, sizeof(int) ); /* alloc mem for the "hand-made" pointer, 100 elements */
  17.   odd_array_alias = odd_array;                   /* remember the original calloc()'d address with odd_array_alias */
  18.   if (odd_array) /* error checking */
  19.   {
  20.     odd_array[0] = 1;  /* make first element the first odd number, 1 */
  21.     even_array[0] = 2; /* make first element the first even number, 2 */
  22.     for (i = 1; i <= 99; i++) /* loop 99 times (element 0 for both arrays are done), fill arrays */
  23.     {
  24.       odd_array[i] = odd_array[i - 1] + 2; /* fill odd array with odd numbers. This line shows a "hand-made" array can be used like a "compiler" one. */
  25.       even_array[i] = even_array[i -1] + 2; /* fill even array with even numbers */
  26.     }
  27.     for (i = 0; i <= 99; i++) /* loop 100 times, display array contents */
  28.     {
  29.       printf("\n#:%i. Odd: %i. Even: %i.", i, *odd_array, *even_array);
  30.       odd_array++; /* Move pointer to next element. */
  31.       even_array++; /* Move pointer to next element. */
  32.     }
  33.     printf("\n\nFirst elements again: Odd: %i Even %i.\n", *odd_array_alias, *even_array); /* This line shows you can still dereference a "fixed" pointer in a "compiler" array */
  34.     free(odd_array_alias); /* Can't use odd_array, since odd_array doesn't point to originally calloc'd address anymore. */
  35.   } /* NB: In your own programming, try to use pointer aliases when you want to modifiable pointer, so you can use the same pointer used for calloc() with free() */
  36.   else printf("\nMemory alloc failed.\n"); /* if odd_array failed on alloc */
  37.  
  38.   return 0;
  39. }